package com.xiaoger.ssologin.controller;

import com.xiaoger.ssologin.pojo.User;
import com.xiaoger.ssologin.utils.LoginCacheUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

/**
 * 页面跳转视图
 *
 * @author xjx
 * @date 2022/3/27 12:23
 */
@Controller
@RequestMapping("/view")
public class ViewController {

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @GetMapping("/login")
    public String toLoogin(@RequestParam(required = false, defaultValue = "") String target,
                           HttpSession session, @CookieValue(required = false, value = "TOKEN") Cookie cookie) {
        if (StringUtils.isEmpty(target)) {
            target = "http://xiaoger.cn:9010";
        }

        if (cookie != null) {
            String value = cookie.getValue();
            User user = LoginCacheUtil.loginUser.get(value);
            if (user != null) {
                return "redirect:" + target;
            }
        }

        //重定向地址
        session.setAttribute("target", target);

        return "login";
    }
}
